package chu.dejian.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.Nullable;

import com.sam.ble.unimplements.BLEBRHelper;
import com.sam.blemodule.R;
import com.sam.ui.base.activity.BaseActivity;
import com.sam.utils.L;
import com.sam.utils.NetUtil;
import com.sam.utils.T;
import com.sam.utils.display.DensityUtils;
import com.sam.widget.badge.BadgeView;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenu;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuCreator;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuItem;
import com.sam.widget.listview.deprecate_menu_list.SwipeMenuListView;

import java.util.ArrayList;
import java.util.List;
import chu.dejian.adapter.AttentionAdapter;
import chu.dejian.db.DBHelper;
import chu.dejian.entity.ContactEntity;
import chu.dejian.entity.ReceivedRequestEntity;
import chu.dejian.models.GetReceivedAttenderRequestResponse;
import chu.dejian.models.PutAttenderRequestRequest;
import chu.dejian.models.PutAttenderRequestResponse;
import chu.dejian.restApi.RestClient;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class ReceivedRequestActivity extends BaseActivity {
	private SwipeMenuListView receivedReqeustListView;
	private List<ContactEntity> attentionRequestList = new ArrayList<>();
	private AttentionAdapter attentionRequestAdapter;

	@Override
	protected void onCreate(@Nullable Intent savedInstanceStateIntent) {
		setContentView(R.layout.fragment_received_request);
	}

	@Override
	public void onResume() {
		super.onResume();
		List<ContactEntity> contactEntities = ReceivedRequestEntity.convertToContactEntity(DBHelper.getInstance().getReceivedRequestDao().getAllRequest());
		attentionRequestList.clear();
		if(contactEntities != null) attentionRequestList.addAll(contactEntities);
		attentionRequestAdapter.notifyDataSetChanged();
		asyncRequest(1);
	}

	public void findView() {
		receivedReqeustListView = (SwipeMenuListView) findViewById(R.id.received_request_listview);
	}

	public void initView() {
		receivedReqeustListView.setMenuCreator(requestMenuCreator);
		receivedReqeustListView.setMenuCreator(requestMenuCreator);
		receivedReqeustListView.setOnMenuItemClickListener(requestMenuClickListener);
		attentionRequestAdapter = new AttentionAdapter(ReceivedRequestActivity.this,R.layout.row_attention_horizontal, attentionRequestList,true);
		receivedReqeustListView.setAdapter(attentionRequestAdapter);
	}

	SwipeMenuCreator requestMenuCreator = new SwipeMenuCreator() {

		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem acceptBtn = new SwipeMenuItem(ReceivedRequestActivity.this);
			Drawable acceptBg = new ColorDrawable(getResources().getColor(R.color.blue_menu_bg_color));
			acceptBtn.setBackground(acceptBg);
			acceptBtn.setWidth(DensityUtils.dp2px(ReceivedRequestActivity.this, 60));
			acceptBtn.setTitle(R.string.accept);
			acceptBtn.setTitleSize(16);
			acceptBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(acceptBtn);

			SwipeMenuItem refuseBtn = new SwipeMenuItem(ReceivedRequestActivity.this);
			Drawable refuseBg = new ColorDrawable(getResources().getColor(R.color.orange_menu_bg_color));
			refuseBtn.setBackground(refuseBg);
			refuseBtn.setWidth(DensityUtils.dp2px(ReceivedRequestActivity.this, 60));
			refuseBtn.setTitle(R.string.refuse);
			refuseBtn.setTitleSize(16);
			refuseBtn.setTitleColor(Color.WHITE);
			menu.addMenuItem(refuseBtn);
		}
	};

	private SwipeMenuListView.OnMenuItemClickListener requestMenuClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
		@Override
		public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
			final int p = attentionRequestList.size()  - 1 - position; // 倒序显示
			final int attentionId = attentionRequestList.get(p).id;
			switch (index) {
				case 0: //接受
					if(!NetUtil.checkNetWork(ReceivedRequestActivity.this)) {
						T.showShort(ReceivedRequestActivity.this,R.string.operation_denied_network_required);
						return false;
					}
					int level = attentionRequestList.get(p).attentionLevel.ordinal();
					PutAttenderRequestRequest putAttenderRequestRequest = new PutAttenderRequestRequest(PutAttenderRequestRequest.ACTION_ID_ACCEPT,level);
					RestClient.getAuthedClient().getApiService().putAttenderRequest(attentionId, putAttenderRequestRequest, new Callback<PutAttenderRequestResponse>() {
						@Override
						public void success(PutAttenderRequestResponse putAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(ReceivedRequestActivity.this);
								T.showShort(ReceivedRequestActivity.this,R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = putAttenderRequestResponse == null ? "null" : putAttenderRequestResponse.toString();
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求成功： \n\t返回数据：" + requestStr );
							if(response.getStatus() == 200){
								attentionRequestList.remove(p);
								attentionRequestAdapter.notifyDataSetChanged();
							} else T.showShort(ReceivedRequestActivity.this, R.string.process_failed);
						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showShort(ReceivedRequestActivity.this, R.string.process_failed);
						}
					});
					break;
				case 1: //拒绝
					if(!NetUtil.checkNetWork(ReceivedRequestActivity.this)) {
						T.showShort(ReceivedRequestActivity.this,R.string.operation_denied_network_required);
						return false;
					}
					putAttenderRequestRequest = new PutAttenderRequestRequest(PutAttenderRequestRequest.ACTION_ID_REFUSE,0);
					RestClient.getAuthedClient().getApiService().putAttenderRequest(attentionId, putAttenderRequestRequest, new Callback<PutAttenderRequestResponse>() {
						@Override
						public void success(PutAttenderRequestResponse putAttenderRequestResponse, Response response) {
							if(response.getStatus() == 401) {
								BLEBRHelper.getInstance().sendReloginBR(ReceivedRequestActivity.this);
								T.showShort(ReceivedRequestActivity.this,R.string.nauthorized_and_relogin);
								return;
							}
							String requestStr = putAttenderRequestResponse == null ? "null" : putAttenderRequestResponse.toString();
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求成功： \n\t返回数据：" + requestStr);
							if(response.getStatus() == 200){
								attentionRequestList.remove(p);
								attentionRequestAdapter.notifyDataSetChanged();
							} else T.showShort(ReceivedRequestActivity.this, R.string.process_failed);

						}

						@Override
						public void failure(RetrofitError retrofitError) {
							L.d("《对关注请求执行操作-putAttenderRequest》", "请求失败： \n\t错误信息：" + retrofitError.toString());
							T.showShort(ReceivedRequestActivity.this, R.string.process_failed);
						}
					});
					break;
			}
			return false;
		}
	};

	private boolean isAnsyncRequest = false;
	private List<ContactEntity> newAttentionRequests = new ArrayList<>();
	private void asyncRequest(int startPage){
		if(isAnsyncRequest) return;
		isAnsyncRequest = true;
		RestClient.getAuthedClient().getApiService().getReceivedAttenderRequest(startPage,new Callback<GetReceivedAttenderRequestResponse>() {
			@Override
			public void success(GetReceivedAttenderRequestResponse getReceivedAttenderRequestResponse, Response response) {
				if(response.getStatus() == 401) {
					BLEBRHelper.getInstance().sendReloginBR(ReceivedRequestActivity.this);
					T.showShort(ReceivedRequestActivity.this,R.string.nauthorized_and_relogin);
					return;
				}
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求成功： \n\t返回数据：" + getReceivedAttenderRequestResponse.toString());
				final List<GetReceivedAttenderRequestResponse.ResultsEntity> resultEntities = getReceivedAttenderRequestResponse.getResults();
				if (resultEntities == null || resultEntities.size() == 0) return;
				for (GetReceivedAttenderRequestResponse.ResultsEntity resultsEntity : resultEntities) {
					ReceivedRequestEntity requestEntity = new ReceivedRequestEntity();
					requestEntity.arId = resultsEntity.getAr_id();
					requestEntity.attendee = resultsEntity.getAttendee();
					requestEntity.attendeeName = resultsEntity.getAttendee_name();
					requestEntity.attendeeLevel = resultsEntity.getAttendee_level();
					requestEntity.status = resultsEntity.getStatus();
					ContactEntity contactEntity = ReceivedRequestEntity.convertToContactEntity(requestEntity);
					if(resultsEntity.getStatus() == ReceivedRequestEntity.STATUS_PENDING && !attentionRequestList.contains(contactEntity)){
						DBHelper.getInstance().getReceivedRequestDao().insertRequest(requestEntity);
						newAttentionRequests.add(contactEntity);
					}
				}
				isAnsyncRequest = false;
				if(getReceivedAttenderRequestResponse.getNext() != null && !getReceivedAttenderRequestResponse.getNext().equals("null")){
					int nextPage = Integer.parseInt(Uri.parse(getReceivedAttenderRequestResponse.getNext()).getQueryParameter("page"));
					asyncRequest(nextPage);
				} else if(newAttentionRequests.size() > 0){
					ReceivedRequestActivity.this.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							attentionRequestAdapter.notifyDataSetChanged();
						}
					});
				}
			}

			@Override
			public void failure(RetrofitError retrofitError) {
				L.d("《获取收到的关注请求-getReceivedAttenderRequest》\n请求失败： \n\t错误信息：" + retrofitError.toString());
				T.showLong(ReceivedRequestActivity.this, R.string.get_data_from_webserver_failed);
			}
		});
	}

}
